//
//  JTDocmentPickerManager.swift
//  Singapore Customer App
//
//  Created by Kiyo on 2021/6/4.
//

import UIKit
import MobileCoreServices

open class JTDocmentPickerManager: NSObject {
    
    static public var iCloudEnable: Bool {
        guard let _ = defaultiCloudURL else { return false }
        return true
    }
    
    static public var defaultiCloudURL: URL? {
        let fileMgr = FileManager.default
        return fileMgr.url(forUbiquityContainerIdentifier: nil)
    }
    
    private let documentTypes: [String] = [
        kUTTypePDF as String,
        kUTTypeRTF as String,
        kUTTypeData as String,
        kUTTypeXML as String,
        kUTTypeJSON as String,
        kUTTypeLog as String,
        kUTTypeSpreadsheet as String,
        kUTTypeText as String
    ]
    
    private var selectFileCallback: ((Data, URL, String)->Void) = {_, _, _ in }
    
    
    
    public func showDocmentVc(_ completionHandler: @escaping ((Data, URL, String)->Void)) {
        
        selectFileCallback = completionHandler
        
        let docmentVc = UIDocumentPickerViewController(documentTypes: documentTypes, in: .open)
        docmentVc.delegate = self
        UIApplication.shared.keyWindow?.rootViewController?.present(docmentVc, animated: true, completion: nil)
    }
}

extension JTDocmentPickerManager: UIDocumentPickerDelegate {
    
    public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        
        guard let fileUrl = urls.first else { return }
        guard fileUrl.startAccessingSecurityScopedResource() else { return }

        do {
            let data = try Data(contentsOf: fileUrl)
            selectFileCallback(data, fileUrl, fileUrl.lastPathComponent)
            
            let size = String(format: "%.2f", Double(data.count)/1024.0/1024.0)
            print("====>  文件名: \(fileUrl.lastPathComponent)")
            print("====>  文件类型: \(fileUrl.pathExtension)")
            print("====>  文件大小: \(size) M")
        } catch {
            fileUrl.stopAccessingSecurityScopedResource()
            print("====>  File Error: \(error)")
        }
    }
}
